package com.storm.lib.runner;

import java.lang.reflect.Method;

import com.storm.lib.base.BaseTask;

import com.storm.lib.template.TaskTemplate;
import com.storm.lib.util.ExceptionUtil;
import com.storm.lib.util.SystemUtil;



/**
*
* 类功能:用来做循环的进程类
* @author johnny
* @version 2010-11-29
*/
public class WhileRunner extends BaseTask{
	private Class clazz;

	public Class getClazz() {
		return clazz;
	}

	public void setClazz(Class clazz) {
		this.clazz = clazz;
	}

	@Override
	public void run() {
		boolean firstTime=true;
		Thread lastInstance = null;
		while (true) {
			if(SystemUtil.isStopped()){
				logger.debug("系统停止,跳过循环任务："+clazz.getName());
				break;
			}
			Long repeatSleepTime=100l;
			  try {
				  //TODO 隐患-这个不是很完善
				  if(lastInstance!=null && lastInstance.isAlive()){
//					  logger.debug("前面的线程活着,继续等待:"+lastInstance.getClass().getSimpleName());
//					  Thread.sleep(repeatSleepTime);
					 continue;
//					 ExceptionUtil.throwInvalidParamException("前面的线程活着:"+lastInstance.getClass().getSimpleName());
				  }
					Object obj = clazz.newInstance();
					lastInstance=(Thread) obj;
					Method m = null;
					m = clazz.getMethod("getRepeatDelayMS", null);
					repeatSleepTime=(Long) m.invoke(obj, new Object[0]);
					ExceptionUtil.checkIfNone(repeatSleepTime);
					if(firstTime){
						m = clazz.getMethod("getFirstDelayMS", null);
						Long firstSleepTime=(Long) m.invoke(obj, new Object[0]);
						ExceptionUtil.checkIfNone(firstTime);
						Thread.sleep(firstSleepTime);
						firstTime=false;
					}
					m = clazz.getMethod("start", null);
					m.invoke(obj, new Object[0]);
//					SystemStatusCache.executedTasks.add((BaseTask) obj);
				} catch (Exception e) {
					ExceptionUtil.processException(e);
				}
				finally{
					try {
						Thread.sleep(repeatSleepTime);
					} catch (InterruptedException e) {
//						logger.debug(getClass().getName()+"被干扰终结");
					}
				}

		}
		logger.debug(clazz.getName()+": i am dead");
	}

}